package models

import (
	"github.com/jinzhu/gorm"
)

type Auth struct {
	Model
	Username string `json:"username" form:"username" valid:"Required;MaxSize(20)"`
	Nickname string `json:"nickname" form:"nickname" valid:"Required;MaxSize(100)"`
	Phone    string `json:"phone" form:"phone" valid:"Phone"`
	Avatar   string `json:"avatar" form:"avatar"`
	Password string `json:"password" form:"password" valid:"Required;MaxSize(20)"`
}

func CheckAuth(phone string) (bool, error) {
	var auth Auth
	err := db.Select("id").Where(Auth{Phone: phone}).First(&auth).Error
	if gorm.IsRecordNotFoundError(err){
		return false,nil
	}
	if err!=nil {
		return true, err
	}
	return true, nil
}

func GetUser(phone string) (*Auth, error) {
	var auth Auth
	err := db.Select("username, nickname,phone").Where("phone = ?", phone).First(&auth).Error
	if gorm.IsRecordNotFoundError(err){
		return nil,err
	}
	if err!=nil {
		return nil, err
	}
	return &auth, nil
}

func AddUser(data map[string]interface{}) error {
	err := db.Create(&Auth{
		Username: data["user_name"].(string),
		Nickname: data["nick_name"].(string),
		Phone:    data["phone"].(string),
		Password: data["password"].(string),
	}).Error
	if err != nil {
		return err
	}
	return nil
}

func IsTelephoneExist(phone string) (bool, error,*Auth) {
	var auth Auth
	err := db.Where("phone=?", phone).First(&auth).Error
	if auth.Phone != "" {
		return true, nil,&auth
	}
	return false, err,nil
}

func IsNicknameExist(nickname string) (bool, error) {
	var auth Auth
	err := db.Where("nickname=?", nickname).First(&auth).Error
	if auth.Nickname != "" {
		return true, nil
	}
	return false, err
}
